package cn.iocoder.yudao.module.system.service.productionplan;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.system.controller.admin.productionplandetail.vo.ProductionPlanDetailRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.productionplandetail.ProductionPlanDetailDO;
import cn.iocoder.yudao.module.system.dal.dataobject.workorder.WorkOrderDO;
import cn.iocoder.yudao.module.system.dal.mysql.productionplandetail.ProductionPlanDetailMapper;
import cn.iocoder.yudao.module.system.dal.mysql.workorder.WorkOrderMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.management.Query;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.system.controller.admin.productionplan.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.productionplan.ProductionPlanDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.system.dal.mysql.productionplan.ProductionPlanMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 生产计划 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class ProductionPlanServiceImpl implements ProductionPlanService {

    @Resource
    private ProductionPlanMapper productionPlanMapper;
    @Resource
    private ProductionPlanDetailMapper productionPlanDetailMapper;
    @Resource
    private WorkOrderMapper workOrderMapper;

    @Override
    public Integer createProductionPlan(ProductionPlanSaveReqVO createReqVO) {
        createReqVO.setNumber(createReqVO.getNumber().trim());
        QueryWrapper<ProductionPlanDO> wrapper = new QueryWrapper<>();
        wrapper.eq("number",createReqVO.getNumber());
        ProductionPlanDO planDO = productionPlanMapper.selectOne(wrapper);
        if (planDO == null) {
            // 插入
            ProductionPlanDO productionPlan = BeanUtils.toBean(createReqVO, ProductionPlanDO.class);
            productionPlanMapper.insert(productionPlan);
            planDO = productionPlan;
        }
        QueryWrapper<ProductionPlanDetailDO> detailDOQueryWrapper = new QueryWrapper<>();
        detailDOQueryWrapper.eq("plan_id",planDO.getId());
        detailDOQueryWrapper.eq("issued",1);

        Long count = productionPlanDetailMapper.selectCount(detailDOQueryWrapper);
        if(count>0){
            throw exception(PRODUCTION_PLAN_ISSUED_NOT_EXISTS2);
        }
        List<ProductionPlanDetailDO> detailDOS =  BeanUtils.toBean(createReqVO.getDetailRespVOS(), ProductionPlanDetailDO.class);
        List<String> specifications = new ArrayList<>();
        for (ProductionPlanDetailDO item:detailDOS) {
            specifications.add(item.getSpecification());
        }
        QueryWrapper<WorkOrderDO> orderDOQueryWrapper = new QueryWrapper<>();
        orderDOQueryWrapper.in("specification",specifications);
        List<WorkOrderDO> orderDOS = workOrderMapper.selectList(orderDOQueryWrapper);
        for (ProductionPlanDetailDO item:detailDOS) {
            item.setPlanId(planDO.getId());
            WorkOrderDO workOrderDO = null;
            for (WorkOrderDO workOrderDO1:orderDOS) {
                if(workOrderDO1.getSpecification().equals(item.getSpecification())){
                    workOrderDO = workOrderDO1;break;
                }
            }
            if(workOrderDO==null){
                throw exception(WORK_ORDER_NOT_EXISTS3);
            }
            item.setCustomerId(workOrderDO.getCustomerId());
            item.setCustomerName(workOrderDO.getCustomerName());
            item.setSupplierName(workOrderDO.getSupplierName());
            item.setProductName(workOrderDO.getProductName());
            item.setSpecification(workOrderDO.getSpecification());
            item.setRack(workOrderDO.getRack());
            item.setRackNumber(workOrderDO.getRackNumber());
            item.setSingleHangingQuantity(workOrderDO.getSingleHangingQuantity());
            item.setSubgroup(workOrderDO.getSubgroup());
            item.setCpDefectNum(workOrderDO.getCpDefectNum());
            item.setFinishedProductNum(workOrderDO.getFinishedProductNum());
        }
        productionPlanDetailMapper.insertBatch(detailDOS);
        // 返回
        return 1;
    }

    @Override
    public void updateProductionPlan(ProductionPlanSaveReqVO updateReqVO) {
        // 校验存在
        validateProductionPlanExists(updateReqVO.getId());
        // 更新
        ProductionPlanDO updateObj = BeanUtils.toBean(updateReqVO, ProductionPlanDO.class);
        productionPlanMapper.updateById(updateObj);
    }

    @Override
    public void deleteProductionPlan(Integer id) {
        // 校验存在
        validateProductionPlanExists(id);
        // 删除
        productionPlanMapper.deleteById(id);
    }

    @Override
        public void deleteProductionPlanListByIds(List<Integer> ids) {
        // 校验存在
        validateProductionPlanExists(ids);
        // 删除
        productionPlanMapper.deleteByIds(ids);
        }

    private void validateProductionPlanExists(List<Integer> ids) {
        List<ProductionPlanDO> list = productionPlanMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(PRODUCTION_PLAN_NOT_EXISTS);
        }
    }

    private void validateProductionPlanExists(Integer id) {
        if (productionPlanMapper.selectById(id) == null) {
            throw exception(PRODUCTION_PLAN_NOT_EXISTS);
        }
    }

    @Override
    public ProductionPlanDO getProductionPlan(Integer id) {
        return productionPlanMapper.selectById(id);
    }

    @Override
    public PageResult<ProductionPlanRespVO> getProductionPlanPage(ProductionPlanPageReqVO pageReqVO) {
        PageResult<ProductionPlanDO> planDOPageResult = productionPlanMapper.selectPage(pageReqVO);
        PageResult<ProductionPlanRespVO> data = BeanUtils.toBean(planDOPageResult, ProductionPlanRespVO.class);
        List<Integer> planIds = new ArrayList<>();
        for (ProductionPlanRespVO item:data.getList()) {
            planIds.add(item.getId());
        }
        if (CollUtil.isNotEmpty(planIds)) {
            QueryWrapper<ProductionPlanDetailDO> detailDOQueryWrapper = new QueryWrapper<>();
            detailDOQueryWrapper.in("plan_id",planIds);
            List<ProductionPlanDetailDO> detailDOS = productionPlanDetailMapper.selectList(detailDOQueryWrapper);

            for (ProductionPlanRespVO item:data.getList()) {
                List<ProductionPlanDetailRespVO> detailRespVOS = new ArrayList<>();
                for(ProductionPlanDetailDO detail:detailDOS){
                    if(item.getId().equals(detail.getPlanId())){
                        ProductionPlanDetailRespVO detailRespVO = BeanUtils.toBean(detail, ProductionPlanDetailRespVO.class);
                        detailRespVOS.add(detailRespVO);
                    }
                }
                item.setDetailRespVOS(detailRespVOS);
            }
        }

        return data;
    }

}
